import React, { ErrorInfo } from 'react';
import DeepSeekHelper from './deepseekhelper';

interface TCommonParams {
    error: Error | null;
    errorInfo: ErrorInfo | null;
    logger?: any[];
    otherParam?: Record<string, any>;
}

interface ErrorBoundaryProps {
    /**
     * @description 自定义降级渲染函数
     */
    fallbackRender?: (params: { state: TCommonParams; onResetErrorBoundary: () => void }) => React.ReactNode;
    /**
     * @description 自定义错误处理函数
     */
    onError?: (params: TCommonParams) => void;
    /**
     * @description 记录请求条数
     */
    recordsFetchNumber?: number;
}
interface ErrorBoundaryState extends TCommonParams {
    hasError: boolean;
}

export default class ErrorBoundary extends React.Component<
    React.PropsWithChildren<ErrorBoundaryProps>,
    ErrorBoundaryState
> {
    logger;

    constructor(props: ErrorBoundaryProps) {
        super(props);
        this.state = { hasError: false, error: null, errorInfo: null, logger: [] };

        // 记录请求条数
        this.logger = new DeepSeekHelper(this.props?.recordsFetchNumber ?? 10);
    }

    private onResetErrorBoundary = () => {
        this.setState({ hasError: false, error: null, errorInfo: null, logger: [] });
    };

    static getDerivedStateFromError(error: Error) {
        // 更新 state 使下一次渲染能够显示降级后的 UI
        return { hasError: true, error, errorInfo: null };
    }

    componentDidCatch(error: Error, errorInfo: ErrorInfo) {
        const reportObject = {
            error,
            errorInfo,
            logger: this.logger.getRecords(),
            otherParam: {
                location: window.location,
            },
        };

        // 上报服务器
        console.log(reportObject);

        this.setState(reportObject);
        this.props?.onError?.(reportObject);
    }

    render() {
        if (this.state.hasError) {
            return this.props.fallbackRender?.({ state: this.state, onResetErrorBoundary: this.onResetErrorBoundary });
        }

        return this.props.children;
    }
}
